<?php
declare (strict_types=1);

namespace app\controller;

use app\BaseController;
use app\helpers\jwt_token;
use app\helpers\traits\ImageUpload;
use app\http\GatewayClient\Gateway;
use think\facade\Config;
use think\Request;
use app\model\User as ModelUser;

class User extends BaseController
{
    use ImageUpload;


    /**
     * @User: 刘海龙
     * @Date: 2021/8/2
     * @Time: 9:10
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 授权登录
     */
    public function wxLogin()
    {
        $data = $this->request->param();
        $type = $this->request->param('type', 'no_verify');
        if ($type === 'no_verify') { //暂无绑定手机号需发送验证码验证
            $redis_key = 'VC_' . $data['mobile'];
            $is_key = $this->redis->EXISTS($redis_key);
            if ($is_key === 0) {
                return $this->response(403, '验证码不存在请重新获取');
            } else {
                $redis_data = json_decode($this->redis->get($redis_key), true);
                $vc = $redis_data['vc'];
                if ($vc != $data['code']) {
                    return $this->response(403, '验证码输入有误,请重新输入');
                }
            }
        }
        $res = \app\model\User::find($this->request->wx_user_id);
        if (is_null($res)) {
            return $this->response(500, '未找到相关信息');
        }
        $res->save($data);
        return $this->response($res->toArray());

    }

    /**
     * @User: 刘海龙
     * @Date: 2021/8/2
     * @Time: 9:42
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 验证用户是否绑定手机号和社区
     */
    public function verifyUser()
    {
        $data = $this->request->param();
        $user = \app\model\User::where(['name'=>$data['name']])->find();
        if (is_null($user)) {
            return $this->response(403, '找不到该用户');
        }
        if ($user['name'] !== $user->name){
            return $this->response(403, '用户名不正确');
        }

        if (!password_verify($data['password'], $user->password)) {
            return $this->response(403, '密码错误');
        }
        $key = $this->token->createToken($user->id);//生成token
        $user->save(['api_token'=>$key]);
//        if (empty($user->mobile) || empty($user->community_id)) {
//            return $this->response(403, '手机号和社区ID为空');
//        }
        return $this->response($user->toArray());
    }


    /**
     * @User: 刘海龙
     * @Date: 2021/7/7
     * @Time: 16:01
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 创建token
     */
    public function getXcxToken()
    {
        $code = $this->request->param('code');
        $wx_url = "https://api.weixin.qq.com/sns/jscode2session?appid=" . Config::get('wechat.xgjd.app_id') . "&secret=" . Config::get('wechat.xgjd.app_secret') . "&js_code=" . $code . "&grant_type=" . Config::get('wechat.xgjd.grant_type') . "";
        $wx_data = $this->http($wx_url, 'get');
        if ($wx_data[0] == 200) {
            $wxResult = json_decode($wx_data[1], TRUE);
            //判空
            if (empty($wxResult)) {
                return $this->response(500, '获取session_key,openID时异常，微信内部错误');
            } else {
                //判断返回的结果中是否有错误码
                if (isset($wxResult['errcode'])) {
                    //如果有错误码，调用抛出错误方法
                    return $this->response(500, $wxResult);
                } else {
                    //1.通过openid 查看用户是否存在
                    $user = \app\model\User::where('openid', $wxResult['openid'])->find();
                    //2判断用户是否存在
                    if (!is_null($user)) {
                        $uid = $user['id'];
                    } else {
                        //如果为空 把openid数据库插入一条
                        $new_user_id = \app\model\User::create(['username' => '', 'openid' => $wxResult['openid'], 'session_key' => $wxResult['session_key']])->id;
                        $uid = $new_user_id;
                    }
                }

            }
            $key = $this->token->createToken($uid);//生成token
            return $this->response(['token' => $key]);
        } else {
            return $this->response(500, '连接微信服务器失败');
        }
    }

    /**、
     * @User: 刘海龙
     * @Date: 2021/7/7
     * @Time: 16:02
     * @return \think\response\Json
     * 验证
     */
    public function tokenVerify()
    {
        $token = $this->request->param('token');
        if (!$token) {
            return $this->response(500, 'token不允许为空');
        }
        $valid = $this->verifyToken($token);
        $arr = ['isValid' => $valid];
        return json($arr);
    }

    //验证Token
    public function verifyToken($token)
    {
        $exist = $this->token->checkTokenJWT($token);
        if ($exist['code'] === 10000) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * @User: 刘海龙
     * @Date: 2021/8/2
     * @Time: 14:52
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 更新用户头像
     */
    public function updateUserHeaderImg()
    {
        if (!$this->request->file('file')) {
            return $this->response(501, '请选择上传文件');
        }
        $file = $this->request->file('file');
        $result = $this->save($file, 'user_head_img');
        $new_path = 'https://xgjd.luduanzhang.cn/storage/' . $result['path'];
        $res = \app\model\User::find($this->request->wx_user_id);
        if (is_null($res)) {
            return $this->response(403, '用户不存在');
        }
        $res->save(['head_img' => $new_path]);
        return $this->response($res->toArray());
    }

    /**
     * @param $data
     * @User: 刘海龙
     * @Date: 2021/8/2
     * @Time: 14:53
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 更新用户信息
     */
    public function saveUser($data)
    {
        $res = \app\model\User::find($data['id']);
        if (is_null($res)) {
            return $this->response(403, '用户不存在');
        }
        $res->save($data);
        return $this->response($res->toArray());
    }


    public function saveUserInfo()
    {
        $data = $this->request->param();
        switch ($data['type']) {
            case "mobile":
                $redis_key = 'VC_' . $data['mobile'];
                $is_key = $this->redis->EXISTS($redis_key);
                if ($is_key === 0) {
                    return $this->response(403, '验证码不存在请重新获取');
                } else {
                    $redis_data = json_decode($this->redis->get($redis_key), true);
                    $vc = $redis_data['vc'];
                    if ($vc != $data['code']) {
                        return $this->response(403, '验证码输入有误,请重新输入');
                    }
                }
                $new_data = [
                    'mobile' => $data['mobile']
                ];
                //验证手机号
                break;
            case "username":
                $new_data = [
                    'name' => $data['username']
                ];
                //更改姓名
                break;
            case "community":
                $new_data = [
                    'community_id' => $data['community_id'],
                    'community_name' => $data['community_name']
                ];
                //更改社区
                break;
            case "password":
                $oldPassword = $data['oldPassword'];
                $user = \app\model\User::find($this->request->wx_user_id);
                if (is_null($user)){
                    return $this->response(403,'暂未找到用户');
                }
                if (!password_verify($oldPassword, $user->password)) {
                    return $this->response(401, '原始密码错误');
                }
                $password = $data['password'];
                $confirmPassword = $data['confirmPassword'];
                if ($password !== $confirmPassword){
                    return $this->response(401, '两次密码输入不一致');
                }
                $new_data = [
                    'password' => password_hash($password,PASSWORD_DEFAULT)
                ];
                break;
            default:
                $new_data = [];
                break;
        }
        $new_data['id'] =  $this->request->wx_user_id;
        return $this->saveUser($new_data);
    }

    //把用户和客户端绑定到一起
    public function bindClientUid()
    {
        $data = $this->request->param('');
        Gateway::bindUid($data['client_id'], $data['uid']);
        return json(array('code' => 200, 'data' => ['message' => '成功']));
    }
}
